<template>
  <div class="note-list-container">
    <!-- 页面标题 -->
    <Header title="笔记列表">
      <template #subtitle>
        <el-tag>{{ getNotes.length }} 条笔记</el-tag>
      </template>
      <template #actions>
        <el-button type="primary" icon="el-icon-plus" @click="handleAddNote">新增笔记</el-button>
      </template>
    </Header>
    
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入标题关键词" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 130px">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="重要性">
          <el-rate
            v-model="searchForm.importance"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="5"
            @change="handleSearch">
          </el-rate>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 笔记列表 -->
    <el-card shadow="hover" class="list-card">
      <el-table
        :data="paginatedNotes"
        style="width: 100%"
        v-loading="loading"
        border
        stripe>
        <el-table-column prop="id" label="ID" width="60" sortable></el-table-column>
        <el-table-column prop="title" label="标题" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="category" label="分类" width="100">
          <template slot-scope="scope">
            <el-tag :type="getCategoryType(scope.row.category)">{{ getCategoryLabel(scope.row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="importance" label="重要性" width="120">
          <template slot-scope="scope">
            <el-rate
              v-model="scope.row.importance"
              disabled
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              :max="5">
            </el-rate>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-view" @click="handleViewNote(scope.row)">查看</el-button>
            <el-button size="mini" type="success" icon="el-icon-edit" @click="handleEditNote(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDeleteNote(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredNotes.length">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 笔记对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :before-close="handleDialogClose">
      <NoteForm
        :note="currentNote"
        :readonly="dialogMode === 'view'"
        :submit-button-text="dialogMode === 'add' ? '新增' : '更新'"
        @submit="handleFormSubmit"
      ></NoteForm>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Header from '@/components/Header.vue'
import NoteForm from '@/components/NoteForm.vue'
import { EventBus, EventNames } from '@/utils/eventBus'

export default {
  name: 'NoteList',
  components: {
    Header,
    NoteForm
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        title: '',
        category: '',
        importance: 0
      },
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      // 对话框配置
      dialogVisible: false,
      dialogMode: 'add', // 'add', 'edit', 'view'
      currentNote: null,
      // 加载状态
      loading: false,
      // 分类选项
      categories: [
        { value: 'work', label: '工作', type: 'primary' },
        { value: 'study', label: '学习', type: 'success' },
        { value: 'life', label: '生活', type: 'warning' },
        { value: 'other', label: '其他', type: 'info' }
      ]
    }
  },
  computed: {
    ...mapGetters(['getNotes']),
    /**
     * 根据搜索条件过滤笔记
     * @returns {Array} 过滤后的笔记列表
     */
    filteredNotes() {
      return this.getNotes.filter(note => {
        // 标题过滤
        const titleMatch = !this.searchForm.title || 
          note.title.toLowerCase().includes(this.searchForm.title.toLowerCase())
        
        // 分类过滤
        const categoryMatch = !this.searchForm.category || 
          note.category === this.searchForm.category
        
        // 重要性过滤
        const importanceMatch = !this.searchForm.importance || 
          note.importance >= this.searchForm.importance
        
        return titleMatch && categoryMatch && importanceMatch
      })
    },
    /**
     * 根据分页配置获取当前页的笔记
     * @returns {Array} 当前页的笔记列表
     */
    paginatedNotes() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredNotes.slice(start, end)
    },
    /**
     * 获取对话框标题
     * @returns {String} 对话框标题
     */
    dialogTitle() {
      const titles = {
        add: '新增笔记',
        edit: '编辑笔记',
        view: '查看笔记'
      }
      return titles[this.dialogMode] || '笔记'
    }
  },
  created() {
    // 监听事件总线上的事件
    EventBus.$on(EventNames.OPEN_NOTE_DIALOG, this.handleAddNote)
    EventBus.$on(EventNames.VIEW_NOTE, this.handleViewNote)
    EventBus.$on(EventNames.EDIT_NOTE, this.handleEditNote)
  },
  beforeDestroy() {
    // 移除事件监听，防止内存泄漏
    EventBus.$off(EventNames.OPEN_NOTE_DIALOG, this.handleAddNote)
    EventBus.$off(EventNames.VIEW_NOTE, this.handleViewNote)
    EventBus.$off(EventNames.EDIT_NOTE, this.handleEditNote)
  },
  methods: {
    /**
     * 处理搜索
     */
    handleSearch() {
      this.pagination.currentPage = 1
    },
    
    /**
     * 重置搜索表单
     */
    resetSearch() {
      this.searchForm = {
        title: '',
        category: '',
        importance: 0
      }
      this.handleSearch()
    },
    
    /**
     * 处理分页大小变化
     * @param {Number} val - 新的页面大小
     */
    handleSizeChange(val) {
      this.pagination.pageSize = val
    },
    
    /**
     * 处理当前页变化
     * @param {Number} val - 新的当前页
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
    },
    
    /**
     * 处理添加笔记
     */
    handleAddNote() {
      this.dialogMode = 'add'
      this.currentNote = {
        title: '',
        category: '',
        tags: [],
        content: '',
        importance: 3
      }
      this.dialogVisible = true
    },
    
    /**
     * 处理查看笔记
     * @param {Object} note - 笔记对象
     */
    handleViewNote(note) {
      this.dialogMode = 'view'
      this.currentNote = { ...note }
      this.dialogVisible = true
    },
    
    /**
     * 处理编辑笔记
     * @param {Object} note - 笔记对象
     */
    handleEditNote(note) {
      this.dialogMode = 'edit'
      this.currentNote = { ...note }
      this.dialogVisible = true
    },
    
    /**
     * 处理删除笔记
     * @param {Object} note - 笔记对象
     */
    handleDeleteNote(note) {
      this.$confirm('确认删除该笔记吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('deleteNote', note.id)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    /**
     * 处理表单提交
     * @param {Object} formData - 表单数据
     */
    handleFormSubmit(formData) {
      if (this.dialogMode === 'add') {
        // 添加笔记
        this.$store.dispatch('addNote', formData)
        this.$message.success('添加成功')
      } else if (this.dialogMode === 'edit') {
        // 更新笔记
        this.$store.dispatch('updateNote', {
          ...formData,
          id: this.currentNote.id
        })
        this.$message.success('更新成功')
      }
      this.dialogVisible = false
    },
    
    /**
     * 处理对话框关闭
     */
    handleDialogClose() {
      this.dialogVisible = false
    },
    
    /**
     * 获取分类标签类型
     * @param {String} category - 分类值
     * @returns {String} 标签类型
     */
    getCategoryType(category) {
      const found = this.categories.find(item => item.value === category)
      return found ? found.type : 'info'
    },
    
    /**
     * 获取分类标签文本
     * @param {String} category - 分类值
     * @returns {String} 标签文本
     */
    getCategoryLabel(category) {
      const found = this.categories.find(item => item.value === category)
      return found ? found.label : category
    }
  }
}
</script>

<style scoped>
.note-list-container {
  padding: 20px 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style>